﻿using System;
using System.Collections.Generic;
using System.Text;
using Core.Domain;

namespace Core.SyntaxAnalysis.Classes
{
    public class IF : Stmt
    {
        private readonly Expr m_condition;
        private readonly Stmt m_elseStmt;
        private readonly Stmt m_thenStmt;

        public IF(Expr condition, Stmt thenStmt, Stmt elseStmt)
        {
            m_condition = condition;
            m_thenStmt = thenStmt;
            m_elseStmt = elseStmt;
        }

        public override bool StmtSemanticCheck(ref List<CompilerError> errors)
        {
            bool error = false;
            try
            {
                var t = m_condition.GetExprType();
                if (!(t is Boolean))
                {
                    error = true;
                    errors.Add(new CompilerError(errors.Count + 1, Resources.SyntaxErrorConditionTypeShouldBeBoolean, m_condition.GetLexem()));
                }
            }
            catch (Exception ex)
            {
                error = true;
                errors.Add(new CompilerError(errors.Count + 1, ex.Message, -1, -1));
            }
            if (!m_thenStmt.SemanticCheck(ref errors))
            {
                error = true;
            }
            if (m_elseStmt != null && !m_elseStmt.SemanticCheck(ref errors))
            {
                error = true;
            }
            return !error;
        }

        public override void StmtGenerate(StringBuilder s)
        {
            int lblElse = Env.NextLabel();
            int lblAfter = Env.NextLabel();
            string exprID = m_condition.Generate(s);
            CodeGenerator.AppendIfNotGoto(s, exprID, lblElse);
            m_thenStmt.Generate(s);
            CodeGenerator.AppendGoto(s, lblAfter);
            CodeGenerator.AppendGoto(s, lblElse);
            if (m_elseStmt != null)
            {
                m_elseStmt.Generate(s);
            }
            CodeGenerator.AppendGoto(s, lblAfter);
        }
    }
}